<!--
Copyright 2013 The Polymer Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<!--
/**
 * @module Polymer UI Elements
 */
/**
 * polymer-ui-toggle-button is a button that has one of two states (ON/OFF).
 * You can tap or drag the button to switch state.
 *
 * Example:
 *
 *     <polymer-ui-toggle-button value="true"></polymer-ui-toggle-button>
 *
 * @class polymer-ui-toggle-button
 */
-->
<polymer-element name="polymer-ui-toggle-button" attributes="value"
    on-tap="toggle" on-trackstart="trackStart" on-track="track" on-trackend="trackEnd" on-flick="flick">
  <template>
    <link rel="stylesheet" href="polymer-ui-toggle-button.css" />
    <div id="toggle" class="toggle">
      <span class="on-label">ON</span>
      <span id="thumb" class="thumb"></span>
      <span class="off-label">OFF</span>
    </div>
  </template>
  <script>
    Polymer('polymer-ui-toggle-button', {
      /**
       * Gets or sets the state, true is ON and false is OFF.
       *
       * @attribute value
       * @type boolean
       * @default false
       */
      value: false,
      ready: function() {
        this.setAttribute('touch-action', 'none');
      },
      toggle: function() {
        this.value = !this.value;
      },
      valueChanged: function() {
        this.classList.toggle('on', this.value);
        this.$.toggle.classList.toggle('on', this.value);
      },
      trackStart: function(e) {
        e.preventTap();
        this.w = this.$.toggle.offsetWidth - this.clientWidth;
        this.$.toggle.classList.add('dragging');
      },
      track: function(e) {
        this.x = Math.max(-this.w, Math.min(0, this.value ? e.dx : e.dx - this.w));
        this.$.toggle.style.left = this.x + 'px';
      },
      trackEnd: function() {
        this.$.toggle.style.left = null;
        this.$.toggle.classList.remove('dragging');
        this.value = Math.abs(this.x) < this.w / 2;
        Platform.flush();
      },
      flick: function(e) {
        this.value = e.xVelocity > 0;
        Platform.flush();
      }
    });
  </script>
</polymer-element>
